var IScroll = require('../libs/iscroll-probe')
var template = require('../libs/template-web')
var listTpl = require('../../templates/pos-tpl.string')

module.exports = {
  doScroll: function () {
    var myScroll = new IScroll('.m-index section', {
        probeType: 3,
        mouseWheel: true
    });
    myScroll.scrollBy(0, -40);

    var head = $('.head img'),
        topImgHasClass = head.hasClass('up');
    var foot = $('.foot img'),
        bottomImgHasClass = head.hasClass('down');

    var currentPage = 1

    myScroll.on('scroll', function () {
        var y = this.y,
            maxY = this.maxScrollY - y;
        if (y >= 0) {
            !topImgHasClass && head.addClass('up');
            return '';
        }
        if (maxY >= 0) {
            !bottomImgHasClass && foot.addClass('down');
            return '';
        }
    });

    myScroll.on('scrollEnd', function () {
        if (this.y >= -40 && this.y < 0) {
            myScroll.scrollTo(0, -40);
            head.removeClass('up');
        } else if (this.y >= 0) {
            head.attr('src', '/images/ajax-loader.gif');
            // ajax下拉刷新数据

            setTimeout(function () {
                myScroll.scrollTo(0, -40);
                head.removeClass('up');
                head.attr('src', '/images/arrow.png');
            }, 1000);
        }

        var maxY = this.maxScrollY - this.y;
        var self = this;
        if (maxY > -100 && maxY < 0) {
            myScroll.scrollTo(0, self.maxScrollY + 40);
            foot.removeClass('down')
        } else if (maxY >= 0) {
            foot.attr('src', '/images/ajax-loader.gif');
            // ajax上拉加载数据
            $.ajax({
              url: '/api/listmore.json',
              data: {
                pageNo: ++currentPage,
                pageSize: 15
              },
              success: function (data) {
                // console.log(data);
                var html = template.render(listTpl, data.content.data.page)
                $('.list ul').append($(html).unwrap())

                myScroll.refresh();

                myScroll.scrollTo(0, self.y + 40);
                foot.removeClass('down');
                foot.attr('src', '/images/arrow.png');
              }
            })
        }
    })
  },
  renderTpl: function (cb) {
    $.ajax({
      url: '/vip/list.php',
      type: 'get',
      data: {
        pageNo: 1,
        pageSize: 15
      },
      success: function (data) {
        // console.log(data);
        cb(template.render(listTpl, data.content.data.page))
      }
    })
  }
}
